package uit.mmt02.noibo;

import java.util.Date;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import android.util.Log;


public class InternalEmailControl 
{
	String server;
	String username;
	String password;
	int smtp_port;
	int getmail_port;
	
	String tag = "Noi bo";
	public InternalEmailControl(String server, String username,
			String password, int smtp_port, int getmail_port) {
		super();
		this.server = server;
		this.username = username;
		this.password = password;
		this.smtp_port = smtp_port;
		this.getmail_port = getmail_port;
	}
	public Message[] getmail()
	{
		Message [] message = null;// message luu toan bo mail nhan duoc
		Properties props = System.getProperties();
		props.setProperty("mail.store.protocol", "pop3");
		try 
		{
			props.put("mail.debug", "true");
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore("pop3");
			store.connect(server,username, password);
			Folder inbox = store.getFolder("Inbox");
			inbox.open(Folder.READ_ONLY);
			message = inbox.getMessages();
			Log.v(tag, "lay mail xong");
			
		} catch (Exception e) 
		{
			// TODO: handle exception
			Log.v(tag,"Loi get mail " + e.toString());
		}
		return message;
	}

	public void send(String sub, String body, String to)
	{
		try {
			Properties props = System.getProperties();
			props.put("mail.smtp.host", server);
			props.put("mail.user", username);
			props.put("mail.password", password);
			//authen neu co
			
			//
			props.put("mail.debug", true);
			Session session = Session.getInstance(props);
			Message mess = new MimeMessage(session);
			mess.setSubject(sub);
			mess.setFrom(new InternetAddress(username));
			mess.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
			mess.setText(body);
			mess.setHeader("Esafe", "UIT MMT02 SonUIT");
			mess.setSentDate(new Date());
			mess.saveChanges();//luu trang thai vao file nhap
			Transport.send(mess);
			Log.v(sub, "send Gmail thanh cong...");
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi gui mail  " + e.toString());
		}
	}

}
